package com.example.administrator.viewpaerdemo;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.example.administrator.viewpaerdemo.adapter.ViewPagerAdapter;
import com.example.administrator.viewpaerdemo.fragment.AFragment;
import com.example.administrator.viewpaerdemo.fragment.BFragment;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ArrayList<Fragment> fragments;

    private String[] str = new String[1];
    private ViewPagerAdapter adapter;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TabLayout tabLayout = findViewById(R.id.tablayout);
        viewPager = findViewById(R.id.viewpager);
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                str = new String[10];
                viewPager.setOffscreenPageLimit(10);
                fragments.clear();
                for (int i = 0; i < 10; i++) {
                    str[i] = i + "页";
                    if (i == 0) {
                        fragments.add(new AFragment());
                    } else {
                        fragments.add(BFragment.getInstence(i));
                    }
                }
                adapter.setData(fragments,str);
                adapter.notifyDataSetChanged();
            }
        });

        fragments = new ArrayList<>();
        fragments.add(new AFragment());
        str[0] = "主页";
        viewPager.setOffscreenPageLimit(1);
        tabLayout.setupWithViewPager(viewPager);
        adapter = new ViewPagerAdapter(getSupportFragmentManager(), fragments, str);
        viewPager.setAdapter(adapter);
    }
}
